package com.fenxiangtech.mall.service.impl;

import com.fenxiangtech.mall.dao.AddressDao;
import com.fenxiangtech.mall.entity.Address;
import com.fenxiangtech.mall.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author zhangjiashun
 */
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;

    @Override
    public boolean saveOrUpdateAddress(Address address) {
        boolean hasAddress = this.hasAddress(address.getUserId());
        int effectedNum = 0;
        if (hasAddress) {
            address.setUpdateTime(new Date().getTime());
            effectedNum = addressDao.updateAddress(address);
        } else {
            effectedNum = addressDao.saveAddress(address);
        }
        return effectedNum > 0;
    }

    @Override
    public Address getAddressByUserID(Long userID) {
        return addressDao.getAddressByUserID(userID);
    }

    private boolean hasAddress(Long userID) {
        Address address = addressDao.getAddressByUserID(userID);
        return address != null;
    }
}
